/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.servlet.admin;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.dao.PostDAO;
import model.dao.ProjectDAO;
import model.dao.ProjectTypeDAO;
import model.dao.ProjectUserDAO;
import model.dao.UserDAO;
import model.dao.service.PostDAOService;
import model.dao.service.ProjectDAOService;
import model.dao.service.ProjectTypeDAOService;
import model.dao.service.ProjectUserDAOService;
import model.dao.service.UserDAOService;
import model.entities.Project;
import model.entities.ProjectType;
import model.entities.ProjectUserDetails;
import model.entities.User;
import util.Constants;

/**
 *
 * @author Admin
 */
public class ProjectManagement extends HttpServlet {

    ProjectDAOService PROJECT_SERVICE = ProjectDAO.getInstance();
    ProjectTypeDAOService TYPE_SERVICE = ProjectTypeDAO.getInstance();
    ProjectUserDAOService PU_SERVICE = ProjectUserDAO.getInstance();

    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String action = request.getParameter("action");
        if (action != null) {
            switch (action) {
                case "requestViewAll":
                    loadProjectlist(request, response);
                    break;
                case "requestAddnew":
                    //loadTylelist(request, response);
                    requestAddnew(request, response);
                    break;
                case "deleteProject":
                    deleteProject(request, response);
                    break;
                    case "requestEdit":
                    requestEdit(request, response);
                    break;
            }
        } else {
            loadProjectlist(request, response);
        }

    }

    private void loadProjectlist(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        List<Project> projectList = PROJECT_SERVICE.getProjects();
        request.setAttribute(util.Constants.PROJECT_LIST, projectList);
        request.setAttribute(util.Constants.PAGE, "projectList");
        request.getRequestDispatcher(util.Constants.URL_ADMIN).forward(request, response);
    }

    private void requestAddnew(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        List<ProjectType> typeList = TYPE_SERVICE.getTypes();
        request.setAttribute(util.Constants.TYPE_SERVICE, typeList);
        request.setAttribute(util.Constants.PAGE, "addnewproject");
        request.getRequestDispatcher(util.Constants.URL_ADMIN).forward(request, response);
    }
  private void requestEdit(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int projectID = Integer.parseInt(request.getParameter("id"));
          List<ProjectType> typeList = TYPE_SERVICE.getTypes();
        request.setAttribute(util.Constants.TYPE_SERVICE, typeList);
        Project projectEdit = PROJECT_SERVICE.getProjectByID(projectID);
        
        if (projectEdit != null) {
            request.setAttribute(util.Constants.Project_EDIT, projectEdit);
        } else {
            request.setAttribute(util.Constants.MSG_RESULT, "Error while load info...");
        }
        //   response.getWriter().print(user.getRole().getRoleName());
        request.setAttribute(util.Constants.PAGE, "editproject");
        
        request.getRequestDispatcher(util.Constants.URL_ADMIN).forward(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        if (request.getCharacterEncoding() == null) {
            request.setCharacterEncoding("UTF-8");
        }
        String action = request.getParameter("submit");
        switch (action) {
            case "CreateProject":
                addProject(request, response);
                break;
            case "UpdateProject":
                updateProject(request, response);
                break;
            case "Search":
                findProject(request, response);
                break;

        }
    }

    private void addProject(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        if (request.getCharacterEncoding() == null) {
            request.setCharacterEncoding("UTF-8");
        }
        String projectName = request.getParameter("projectName");
        
        String day = request.getParameter("day");
        String month = request.getParameter("month");
        String year = request.getParameter("year");
        Date startDate = util.Support.convertToDate(day, month, year);
        
        String dtype = request.getParameter("dtype");
        int value = Integer.parseInt(request.getParameter("duration"));
        int duration;
        switch (dtype) {
            case "day":
                duration = value;
                break;
            case "week":
                duration = value * 7;
                break;
            default:
                duration = value * 30;
                break;
        }
        
        String projectType = request.getParameter("projectType");
        String description = request.getParameter("description");
        ProjectType type = TYPE_SERVICE.getTypeByName(projectType);

        Project project = new Project(1, projectName, description, startDate, duration, type, true);
        if (PROJECT_SERVICE.createProject(project)) {
            User user = (User) request.getSession().getAttribute(util.Constants.CURRENT_USER);
            if (user == null) {
                response.getWriter().print("Đăng nhập lại");
            } else {
                List<Project> projectList = PROJECT_SERVICE.getProjectByName(projectName);
                Project p = projectList.get(projectList.size() - 1);
                ProjectUserDetails pud = new ProjectUserDetails(1, user, p, true);
                PU_SERVICE.createPUD(pud);
                   response.sendRedirect("/JudiBlog"+Constants.URL_PROJECTMANAGE);
            }
        } else {
            response.getWriter().print("FAILED");
        }
    }

    private void updateProject(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        if (request.getCharacterEncoding() == null) {
            request.setCharacterEncoding("UTF-8");
        }
       String projectID =  request.getParameter("id");
       int id = Integer.valueOf(projectID);
        String projectName = request.getParameter("projectName");        
        String day = request.getParameter("StartDate");
        
        String dtype = request.getParameter("dtype");
        int value = Integer.parseInt(request.getParameter("duration"));
        int duration;
        switch (dtype) {
            case "day":
                duration = value;
                break;
            case "week":
                duration = value * 7;
                break;
            default:
                duration = value * 30;
                break;
        }
        String projectType = request.getParameter("projectType");
        String description = request.getParameter("description");
        ProjectType type = TYPE_SERVICE.getTypeByName(projectType);

        Project project = new Project(id, projectName, description, Date.valueOf(day), duration, type, true);
        if (PROJECT_SERVICE.updateProject(project)) {
            User user = (User) request.getSession().getAttribute(util.Constants.CURRENT_USER);
            if (user == null) {
                response.getWriter().print("Đăng nhập lại");
               
            } else {
//                List<Project> projectList = PROJECT_SERVICE.getProjectByName(projectName);
//                Project p = projectList.get(projectList.size() - 1);
//                ProjectUserDetails pud = new ProjectUserDetails(1, user, p, true);
//                PU_SERVICE.updatePUD(pud);
                response.sendRedirect("/JudiBlog" +Constants.URL_PROJECTMANAGE);
                
            }
        } else {
//            response.getWriter().print("FAILED");
        }

    }

    private void findProject(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String key = request.getParameter("key");
        String value = request.getParameter("value");
        List<Project> projectList = PROJECT_SERVICE.findProject(key, value);
        if (projectList.isEmpty()) {
            request.setAttribute(util.Constants.MSG_RESULT, "No result for " + value);
        } else {
            request.setAttribute(util.Constants.PROJECT_LIST, projectList);
        }
        request.setAttribute(util.Constants.PAGE, "projectList");
        request.getRequestDispatcher(util.Constants.URL_ADMIN).forward(request, response);

    }

    private void deleteProject(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, ServletException, IOException {

        int projectID = Integer.parseInt(request.getParameter("id"));
        Project project = PROJECT_SERVICE.getProjectByID(projectID);
        if (PROJECT_SERVICE.deleteProject(projectID)) {
            System.out.println("Delete project");
            loadProjectlist(request, response);
        } else {
            request.setAttribute(util.Constants.MSG_RESULT, "Can't delete Project!!!");
        }

    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
